/**
 * 一个小工具，rgb颜色按比例缩减 
 */

// 十进制转十六进制
function decToHex(val) {
  const chars = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'];
  const queue = [];
  let m
  while (val) {
    m = val % 16;
    queue.unshift(chars[m]);
    val = Math.floor(val / 16);
  }

  return queue.join('');
}

// 十六进制转十进制
function hexToDec(val) {
  return parseInt(val, 16);
}

function splitColor(color) {
  const rStr = color.substring(1, 1 + 2);
  const gStr = color.substring(3, 3 + 2);
  const bStr = color.substring(5, 5 + 2);

  return [rStr, gStr, bStr]; // [r, g, b]
}

// color: #aabbcc
// ratio: 0.2
module.exports = function calc(color, ratio) {
  // 拆分
  const [rStr, gStr, bStr] = splitColor(color);

  // 16进制转换10进制
  let r = hexToDec(rStr, 16);
  let g = hexToDec(gStr, 16);
  let b = hexToDec(bStr, 16);
  
  // 计算
  r = Math.floor(r * (1 + ratio));
  g = Math.floor(g * (1 + ratio));
  b = Math.floor(b * (1 + ratio));

  // 10进制转16进制
  const rStrNew = decToHex(r);
  const gStrNew = decToHex(g);
  const bStrNew = decToHex(b);

  return `#${rStrNew.padStart(2, '0')}${gStrNew.padStart(2, '0')}${bStrNew.padStart(2, '0')}`;
}
